package net.melon.agency.pojo.dto.impl;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import net.esj.auth.pojo.CoreAuthFunc;
import net.esj.background.support.BgMenu;
import net.esj.basic.core.view.tools.ActionContext;
import net.esj.basic.dao.querybuilder.QueryBuilder;
import net.esj.basic.pojo.op.Operator;
import net.esj.basic.pojo.system.UserRule;
import net.esj.basic.service.impl.DefaultServiceImpl;
import net.esj.basic.service.provider.UserRuleProvider;
import net.melon.agency.inst.ssh.service.AuthService;
import net.melon.agency.pojo.AgencyUser;
import net.melon.agency.pojo.dto.AgencyMenu;

import org.apache.commons.lang.StringUtils;

@Singleton
@Named("agencyMenu")
public class AgencyMenuImpl extends DefaultServiceImpl implements AgencyMenu {

	private AuthService authService;

	/**
	 * true ：每次都重新加载
	 */
	private boolean reload = false;
	
	@Override
	public Set<BgMenu> getMenus() {
		Set<BgMenu> menus;
		Map userBag = (Map) ActionContext.getSession().getAttribute(getSessionBag());
		if(!isReload()){
			if(userBag!=null){
				menus =(Set<BgMenu>) userBag.get(AGENCY_MENU_SESSION_KEY);
				if(menus!=null){
					return menus;
				}
			}
		}
		AgencyUser user= (AgencyUser) ActionContext.getSession().getAttribute(getSessionKey());
		if(user==null){
			return Collections.EMPTY_SET;
		}
		menus = new TreeSet<BgMenu>(new Comparator<BgMenu>() {
			@Override
			public int compare(BgMenu o1, BgMenu o2) {
				return ((AgencyBgMenu)o1).getSort()-((AgencyBgMenu)o2).getSort();
			}
		});
		Set<CoreAuthFunc> allFuncs ;
		if(user.isSuper()){
			QueryBuilder<CoreAuthFunc> qb = createQueryBuilder(CoreAuthFunc.class);
			qb.eq("model.id", UserRuleProvider.getUserRule(AgencyUser.class).getAuthModel()).eq("disabled", false).OrderByAsc("sort");
			List<CoreAuthFunc> list = queryListByQueryBuilder(qb);
//			Collections.sort(list, new Comparator<AtAgencyFunc>() {
//
//				@Override
//				public int compare(AtAgencyFunc o1, AtAgencyFunc o2) {
//					return o1.getSort()-o2.getSort();
//				}
//			});
			allFuncs = new LinkedHashSet<CoreAuthFunc>(list);
		}else{
			user = authService.getUserWithAuth(user.getId());
			allFuncs = user.getFuncs();
		}
		for(CoreAuthFunc func : allFuncs){
			if(func.getParent()==null){//根目录
				BgMenu root = new AgencyBgMenu(func); 
				menus.add(root);
				setChild(root, allFuncs);
			}
		}
		if(userBag==null){
			userBag = new HashMap();
		}
		userBag.put(AGENCY_MENU_SESSION_KEY, menus);
		ActionContext.getSession().setAttribute(getSessionBag(), userBag);
		return menus;
	}

	private void setChild(BgMenu parent ,Collection<CoreAuthFunc> list){
		for(CoreAuthFunc bm : list){
			if(bm.getParent()!=null &&  StringUtils.equals(bm.getParent().getId(), parent.getId())){
				BgMenu m = new AgencyBgMenu(bm);
				parent.getChildMenus().add(m);
				if(m.isMenu()){
					setChild(m, list);
				}
			}
		}
	}
	
	public boolean isReload() {
		return reload;
	}

	public void setReload(boolean reload) {
		this.reload = reload;
	}
	
	protected String getSessionKey(){
		UserRule rule = UserRuleProvider.getUserRule(AgencyUser.class);
		if(rule!=null){
			return rule.getSessionKey();
		}
		return null;
	}
	
	protected String getSessionBag(){
		UserRule rule = UserRuleProvider.getUserRule(AgencyUser.class);
		if(rule!=null){
			return rule.getSessionBag();
		}
		return null;
	}

	@Inject
	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}

	@Override
	public String getLoginMessage() {
		Object o = ActionContext.getSession().getAttribute(getSessionKey());
		if(o instanceof AgencyUser){
			/*boolean b = matService.hasOrder((Operator) o);
			if(b){
				return "您有新的<a style=\"color:RED\" href=\"javascript:;;\" onclick=\"javascript:layout_center_addTabFun({title : '我的补货单',closable : true,iconCls : 'icon-reload',href : '/agency/mat/myorder-index.htm'});\"  >补货单</a>，请赶紧处理";
			}*/
			return "您有新的<a style=\"color:RED\" href=\"javascript:;;\" onclick=\"javascript:layout_center_addTabFun({title : '我的补货单',closable : true,iconCls : 'icon-reload',href : '/agency/mat/myorder-index.htm'});\"  >补货单</a>，请赶紧处理";
		}
		return "";
	}
}
